package com.shura.ssm.controller;

import com.alibaba.fastjson.JSON;
import com.shura.ssm.common.entity.User;
import com.shura.ssm.service.UserService.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * IndexController
 * Created by shura
 * Date：2017/9/4
 * Time：16:57
 */
@Controller
@RequestMapping("")
public class IndexController extends AbstractController{

    @Resource
    private UserService userService;

    /**
     * 登录状态验证
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"", "/", "login"}, method = RequestMethod.GET)
    public String toLogin(HttpServletRequest request)
    {
        //判断session中是否存在user若存在允许进入主页若没有跳转至登陆
        if (request.getSession().getAttribute("user") != null){
            return "index";
        }
        else {
            return "login";
        }
    }

    @RequestMapping(value = {"index"}, method = RequestMethod.GET)
    public String toIndex() {
        return "index";
    }

    /**
     * 登陆
     *
     * @param user
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "ajax/login", method = RequestMethod.POST)
    @ResponseBody
    public JSON login(User user, Model model, HttpServletRequest request) throws Exception{
        try {
            //登录验证若成功将user存入session
            if (userService.checkLogin(user)) {
                request.getSession().setAttribute("user", user);
                return sendCode(AJAX_SUCCESS_CODE);
            }
            //若登陆验证失败重新跳转回去登录页
            else{
                model.addAttribute("login_err", "登录失败!");
                return sendMsgAndCode(AJAX_FAILED_CODE,"用户名或密码有误，请重新输入！");
            }
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return sendMsgAndCode(AJAX_FAILED_CODE,"登录错误");
        }
    }

    //退出登录页
    @RequestMapping(value = {"logoff"}, method = RequestMethod.GET)
    public String logoff(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "redirect:login";
    }
}
